<template>
  <div class="history-trends">
    <!-- 时间范围选择和指标选择 -->
    <div class="time-filter">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        style="width: 300px;"
      />
      <el-select v-model="selectedMetric" placeholder="请选择指标" class="select-metric">
        <el-option
          v-for="(label, key) in metricLabels"
          :key="key"
          :label="label"
          :value="key"
        />
      </el-select>
      <el-button type="primary" @click="refreshChart">更新图表</el-button>
    </div>

    <!-- ECharts 图表 -->
    <div ref="chartContainer" class="chart-container" />
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  name: 'PollutantTrends',
  setup() {
    const chartContainer = ref(null);
    const dateRange = ref([]);
    const selectedMetric = ref('hma_stationsselenium_selenium');
    const rawData = ref([]);
    const metricData = ref([]);
    const metricLabels = ref({
      hma_stationsselenium_selenium: '锑 (Sb) 浓度',
      hma_stationsarsenic: '砷 (As) 浓度',
      hma_stationscopper: '铜 (Cu) 浓度',
      hma_stationsbarium: '钡 (Ba) 浓度',
      hma_stationscadmium: '镉 (Cd) 浓度',
      hma_stationschromium: '铬 (Cr) 浓度',
      hma_stationsplumbum: '铅 (Pb) 浓度',
      hma_stationsmercury: '汞 (Hg) 浓度',
      hma_stationsmanganese: '锰 (Mn) 浓度',
      hma_stationsnickel: '镍 (Ni) 浓度',
      hma_stationssilver: '银 (Ag) 浓度',
      hma_stationsborate: '硼酸盐',
      hma_stationsnitrate: '硝酸盐',
      hma_stationsfluoride: '氟化物',
      hma_stationsoxygen_demand: '耗氧量',
      hma_stationsvolatile_phenol: '挥发酚',
      hma_stationscyanide: '氰化物',
      hma_stationsanionic_detergent: '阴离子合成洗涤剂',
      hma_stationsmineral_oil: '矿物油',
      hma_stationsnitrite: '亚硝酸盐',
      hma_stationsbromate: '溴酸盐',
      hma_stationstotal_radioactivity: '总放射性',
      hma_stationsradium_226_radioactivity: '226镭放射性',
    });

    // 加载数据
    const loadData = async () => {
      try {
        const response = await axios.get('/csv/hma_pollutant_output.json');
        rawData.value = response.data;

        // 格式化时间
        rawData.value.forEach((item) => {
          item.create_time = item.create_time.split(' ')[0];
          item.update_time = item.update_time.split(' ')[0];
        });

        // 初始化指标数据
        const availableMetrics = Object.keys(rawData.value[0] ?? {});
        for (const key of availableMetrics) {
          if (metricLabels.value[key]) {
            metricData.value = rawData.value.map((item) => ({
              date: item.create_time,
              [key]: parseFloat(item[key] || 0),
            }));
          }
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        ElMessage.error('加载数据失败，请检查文件路径或网络连接');
      }
    };

    // 渲染图表
    const renderChart = (dates, values, title) => {
      const chart = echarts.init(chartContainer.value);

      // 计算单指数平滑
      const smoothData = calculateSingleExponentialSmoothing(values, 0.3);

      const option = {
        title: {
          text: title,
          left: 'center',
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: dates,
          position: 'bottom',
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
            },
          },
        },
        series: [
          {
            name: '原始数据',
            type: 'line',
            data: values,
            smooth: true,
            symbol: 'circle',
            symbolSize: 5,
            lineStyle: {
              width: 2,
            },
          },
          {
            name: '单指数平滑',
            type: 'line',
            data: smoothData,
            smooth: true,
            symbol: 'emptyCircle',
            symbolSize: 5,
            lineStyle: {
              color: 'red',
              width: 2,
            },
          },
        ],
        grid: {
          left: '3%',
          right: '3%',
          bottom: '10%',
          containLabel: true,
        },
        legend: {
          data: ['原始数据', '单指数平滑'],
          right: '10px',
          top: '10px',
        },
      };

      chart.setOption(option);
    };

    // 单指数平滑算法
    const calculateSingleExponentialSmoothing = (data, alpha) => {
      const result = [];
      let prevSmoothed = data[0];
      result.push(prevSmoothed);

      for (let i = 1; i < data.length; i++) {
        const smoothed = alpha * data[i] + (1 - alpha) * prevSmoothed;
        result.push(smoothed);
        prevSmoothed = smoothed;
      }

      return result;
    };

    // 更新图表
    const refreshChart = () => {
      const [startDate, endDate] = dateRange.value;
      const metric = selectedMetric.value;

      // 过滤数据
      const filteredData = rawData.value.filter((item) => {
        const date = new Date(item.create_time);
        return (startDate && date >= new Date(startDate)) && (endDate && date <= new Date(endDate));
      });

      if (filteredData.length === 0) {
        ElMessage.warning('在指定日期范围内没有数据！');
        return;
      }

      const dates = filteredData.map((item) => item.create_time);
      const values = filteredData.map((item) => parseFloat(item[metric] || 0));

      // 渲染图表
      renderChart(dates, values, metricLabels.value[metric]);
    };

    onMounted(() => {
      loadData();
    });

    return {
      chartContainer,
      dateRange,
      selectedMetric,
      refreshChart,
    };
  },
};
</script>

<style scoped>
.history-trends {
  padding: 20px;
  height: 100%;
}

.time-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.chart-container {
  margin-top: 20px;
  width: 100%;
  height: 600px;
}

.select-metric {
  width: 300px;
}
</style>